using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using NLog.Web;

namespace sgf.server
{
    public class WebSocketServer
    {
        private WebApplication app { get; set; }

        public async Task Start(string url, Action<NetChannel> onConnect, Action<long, byte[]> onMessage,
            Action<NetChannel> onDisConnect)
        {
            var builder = WebApplication.CreateBuilder();
            builder.WebHost.UseUrls(url).UseNLog();
            app = builder.Build();

            app.UseWebSockets();

            var webSocketConnectionHandler = new WebSocketConnectionHandler(onConnect, onMessage, onDisConnect);
            app.Map("/ws", async context =>
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                    var clientAddress = $"{context.Connection?.RemoteIpAddress}:{context.Connection?.RemotePort}";
                    await webSocketConnectionHandler.OnConnectedAsync(webSocket, clientAddress);
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                }
            });
            LogMgr.Info("启动websocket服务...");
            await app.StartAsync();
        }
    }
}